package com.zhan.ielts.web.controller;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import com.zhan.frame.core.utils.AliyunOssUtil;
import com.zhan.frame.core.utils.FileUtils;
import com.zhan.frame.core.utils.UUIDUtils;
import com.zhan.frame.core.web.domain.Result;
import com.zhan.ielts.domain.ZhentiCompositionAdd;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.zhan.frame.core.dao.BaseService;
import com.zhan.frame.core.web.controller.BaseControllerImpl;
import com.zhan.frame.core.web.domain.CustomResult;
import com.zhan.ielts.domain.ZhentiComposition;
import com.zhan.ielts.domain.query.ZhentiCompositionQuery;
import com.zhan.ielts.domain.vo.ZhentiCompositionVo;
import com.zhan.ielts.service.UsersService;
import com.zhan.ielts.service.ZhentiCompositionService;
import com.zhan.ielts.utils.CustomPropertisUtils;

import javax.ws.rs.QueryParam;

@Controller
@RequestMapping("/zhenti/composition")
public class ZhentiCompositionController extends BaseControllerImpl<ZhentiComposition, ZhentiCompositionQuery> {

	private Logger log = LoggerFactory.getLogger(ZhentiCompositionController.class);

	@Autowired
	private ZhentiCompositionService zhentiCompositionService;

	@Autowired
	private UsersService usersService;

	@Override
	protected BaseService<ZhentiComposition> getBaseService() {
		return zhentiCompositionService;
	}

	@Override
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView selectList(ZhentiCompositionQuery query, @PageableDefault Pageable pageable) {
		if (!StringUtils.isEmpty(query.getCompositionDate())) {
			if (query.getCompositionDate().length() >= 4) {
				query.setYear(query.getCompositionDate().substring(0, 4));
			}
			if (query.getCompositionDate().length() >= 6) {
				query.setMonth(query.getCompositionDate().substring(5, 7));
			}
			if (query.getCompositionDate().length() >= 8) {
				query.setDay(query.getCompositionDate().substring(8, 10));
			}
		}
		Page<ZhentiComposition> page = getBaseService().queryPageList(query, pageable);
		ModelAndView mav = new ModelAndView(path.getListViewPath(), "page", page);
		mav.addObject("query", query);
		return mav;
	}

	@SuppressWarnings({ "rawtypes" })
	@ResponseBody
	@RequestMapping(value = "/fetch", method = RequestMethod.POST)
	public CustomResult fetchZhentiComposition(String userId, long updateTime) {
		log.debug("获取真题写作开始");

		Map map = new HashMap();
		// 检查userId 是否为空
		if (StringUtils.isEmpty(userId)) {
//			return new CustomResult(0, "userId为空！", map);
		}

		// 检查userId 是否有效
//		Users query = new Users();
//		query.setId(userId);
//		if (usersService.queryCount(query) < 1) {
//			return new CustomResult(0, "userId无效！", map);
//		}

		try {
			ZhentiCompositionVo zhentiComposition = new ZhentiCompositionVo();
			zhentiComposition.setUpdateTime(updateTime);
			Sort sort = new Sort(Direction.DESC, "updateTime").and(new Sort(Sort.Direction.DESC, "id"));
			Pageable pageable = new PageRequest(0, 100, sort);

			map = zhentiCompositionService.fetchZhentiComposition(zhentiComposition, pageable);
			log.debug("获取真题写作结束");
		} catch (Exception e) {
			e.printStackTrace();
			return new CustomResult(0, "网络或系统错误！", map);
		}

		return new CustomResult(1, "", map);

	}

	@ResponseBody
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String update(@RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
		log.debug("zhentiComposition导入操作开始！");

		String fileFolder = CustomPropertisUtils.getProperties("filePath");
		String aliyunFolder = CustomPropertisUtils.getProperties("aliyunZhentiCompositionPath");

		boolean flag = true;
		boolean questionFlag = file.isEmpty();

		if (file.isEmpty()) {
			return "excel can not be null.";
		}

		if (!questionFlag) {
			flag = zhentiCompositionService.updateZhentiComposition(file, fileFolder);

			if (!flag) {
				return "fail to explain excel.";
			}

		}

		log.debug("zhentiComposition导入操作结束！");

		return "success!";

	}

	/**
	 * 将文件保存到本地
	 * @param file 需要保存的文件
	 * @param path 保存的路劲
	 * @param fileName 保存的文件名
	 * @return 保存后的文件
	 * @throws IOException
	 */
	private File saveFile(MultipartFile file, String path, String fileName) throws IOException {
		File targetFile = new File(path, fileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		// 保存
		file.transferTo(targetFile);
		return targetFile;
	}

	/**
	 * 获取文件的后缀
	 * @param fileName
	 * @return
	 */
	private String getImageBackFix(String fileName){
		int idx = fileName.lastIndexOf(".");
		return fileName.substring(idx);
	}

	/**
	 * 从url中获取文件名
	 * @param fileUrl
	 * @return
	 */
	private String getFileNameFromUrl(String fileUrl){
		int idx = fileUrl.lastIndexOf("/");
		return fileUrl.substring(idx + 1);
	}

	@RequestMapping(value = "/addComposition", method = RequestMethod.POST)
	public ModelAndView addComposition(ZhentiCompositionAdd composition) {
		log.debug(composition.toString());
		try {
			String type = composition.getCompositionType();
			composition.setUpdateTime(System.currentTimeMillis());
			String date = composition.getYear();
			date = date.replaceAll("[^\\d]+", "");
			composition.setYear(date.substring(0, 4));
			composition.setMonth(date.substring(4, 6));
			composition.setDay(date.substring(6, 8));
			composition.setId(date + composition.getForm() + type);

			if("l".equals(type)){//小作文，有图片
				if(composition.getImageFile() == null || composition.getImageFile().isEmpty()){//图片为空
					return new ModelAndView(path.getRedirectListPath());
				}
				String imageUrl = uploadFile(composition.getImageFile(), date, composition.getForm());
				composition.setImageUrl(imageUrl);
				composition.setCompositionType("小作文");
			}else{
				composition.setCompositionType("大作文");
			}

			zhentiCompositionService.insert(composition);
		} catch (Exception e) {
			return new ModelAndView(path.getRedirectListPath());
		}
		ModelAndView mav = new ModelAndView(path.getRedirectListPath());
		return mav;
	}

	/**
	 * 上传文件并返回地址
	 * @param multipartFile
	 * @param form
	 * @param date
	 * @throws IOException
	 */
	private String uploadFile(MultipartFile multipartFile, String date, String form) throws IOException {
		String fileFolder = CustomPropertisUtils.getProperties("filePath");
		String aliyunFolder = CustomPropertisUtils.getProperties("aliyunZhentiCompositionPath");
		String fileName = date + form + getImageBackFix(multipartFile.getOriginalFilename());
		File localFile = saveFile(multipartFile, fileFolder + "zhenti/composition/", fileName);
		AliyunOssUtil.uploadFile(localFile, aliyunFolder + "image/");
		return "http://dl.tiku.zhan.com/test/ielts/ZhentiComposition/image/" + URLEncoder.encode(fileName, "utf-8");
	}

	@RequestMapping(value = "/editComposition", method = RequestMethod.POST)
	public ModelAndView editComposition(ZhentiCompositionAdd composition) {
		log.debug(composition.toString());
		try {
			String type = composition.getCompositionType();
			composition.setUpdateTime(System.currentTimeMillis());
			String date = composition.getYear();
			date = date.replaceAll("[^\\d]+", "");
			composition.setYear(date.substring(0, 4));
			composition.setMonth(date.substring(4, 6));
			composition.setDay(date.substring(6, 8));
			if("l".equals(type)){//小作文，有图片
				if(composition.getImageFile() == null || composition.getImageFile().isEmpty()){//图片为空
					if(StringUtils.isEmpty(composition.getImageUrl())) {//小作文必须传图片文件
						return new ModelAndView(path.getRedirectListPath());
					}
				}else {
					if(!StringUtils.isEmpty(composition.getImageUrl())) {//之前存在图片，修改后需要删除之前的图片
						String fileUrl = composition.getImageUrl();
						String aliyunFolder = CustomPropertisUtils.getProperties("aliyunZhentiCompositionPath");
						AliyunOssUtil.deleteFile(aliyunFolder + "image/" + URLDecoder.decode(getFileNameFromUrl(fileUrl)));
					}
					String imageUrl = uploadFile(composition.getImageFile(), date, composition.getForm());
					composition.setImageUrl(imageUrl);
				}
				composition.setCompositionType("小作文");
			}else{
				composition.setCompositionType("大作文");
			}
			zhentiCompositionService.updateById(composition);
		} catch (Exception e) {
			return new ModelAndView(path.getRedirectListPath());
		}
		ModelAndView mav = new ModelAndView(path.getRedirectListPath());
		return mav;
	}

	@ResponseBody
	@RequestMapping(value = "/deleteComposition/{id}")
	public Result deleteComposition(@PathVariable("id") String id) {
		try {
			ZhentiComposition composition = zhentiCompositionService.queryById(id);
			if(composition != null) {
				if (!StringUtils.isEmpty(composition.getImageUrl())) {//之前存在图片，修改后需要删除之前的图片
					String fileUrl = composition.getImageUrl();
					String aliyunFolder = CustomPropertisUtils.getProperties("aliyunZhentiCompositionPath");
					AliyunOssUtil.deleteFile(aliyunFolder + "image/" + URLDecoder.decode(getFileNameFromUrl(fileUrl)));
				}
				deleteOne(id);
			}
		}catch (Exception e){
			return new Result(Result.Status.ERROR, 0);
		}
		return new Result(Result.Status.OK, 1);
	}
}
